package cn.xspace.module.other.activity;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.module.other.R;
import cn.xspace.module.other.bean.FavoriteFolderBean;
import cn.xspace.module.other.R;
import cn.xspace.module.other.bean.FavoriteFolderBean;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MoveFavFolderActivity extends BaseActivity {

    private static final String TAG = MoveFavFolderActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private ListView mListView;
    private String user_id;

    private List<FavoriteFolderBean> parentList = new ArrayList<>();
    private MoveFolderAdapter adapter;
    private String fromFolderId;
    private String fromParentId;

    @Override
    protected void getIntentData() {
        fromFolderId = getIntent().getStringExtra("folderId");
        fromParentId = getIntent().getStringExtra("parentId");
        LogUtil.d(TAG, "wubaojie>>>getIntentData: folder_id:" + fromFolderId);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_move_fav_folder);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.fav_move_folder_title);
        mTitleBar.setRightLayoutVisibility(View.GONE);
        mTitleBar.setTitle(ResourceUtils.getString(R.string.move_fav_folder));
        mListView = (ListView) findViewById(R.id.fav_move_folder);
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        refreshList();
        queryAllFolder();
    }

    private void refreshList() {
        if (adapter == null) {
            adapter = new MoveFolderAdapter();
            mListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private void queryAllFolder() {
        showWaitDialog();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(RequestConstant.KEY_USER_ID, user_id);
        hashMap.put(RequestConstant.FOLDER_ID, null);
        OkHttpManager.getInstance().commonJsonPost(Constants.QueryFavoriteFolder, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray jsonArray = jsonObject.optJSONArray("folderList");
                            parseQueryAllFolder(jsonArray);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void parseQueryAllFolder(JSONArray jsonArray) {
        try {
            parentList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject js = jsonArray.getJSONObject(i);
                String folder_name = js.optString("folder_name");
                String folder_id = js.optString("folder_id");
                String isleaf = js.optString("isleaf");
                FavoriteFolderBean ffb_temp = new FavoriteFolderBean(folder_name, folder_id, isleaf);
                parentList.add(ffb_temp);
            }
            parentList.add(new FavoriteFolderBean(true));
            hideWaitDialog();
            refreshList();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FavoriteFolderBean bean = parentList.get(position);
                if (bean.getFolderId().equals(fromParentId)) {
                    T.showShort(mContext, R.string.is_in_folder);
                } else {
                    changeFavorieFolder(bean);
                }
            }
        });
    }

    /**
     * 移动收藏夹
     *
     * @param bean
     */
    public void changeFavorieFolder(final FavoriteFolderBean bean) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put(RequestConstant.KEY_USER_ID, user_id);
        map.put(RequestConstant.FOLDER_ID, fromFolderId);
        map.put(RequestConstant.FOLDER_PARENT, bean.getFolderId());

        OkHttpManager.getInstance().commonJsonPost(Constants.ChangeFavoriteFolder, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, R.string.network_error);
                    }

                    @Override
                    public void onNext(String s) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>onNext: " + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.optString("code");
                            if ("0".equals(code)) {
                                MyFavoriteManagerActivity.isNeedRefresh = true;
                                MyFavoriteActivity.isNeedRefresh = true;
                                T.showShort(mContext, "移动成功");
                                finish();
                            } else {
                                T.showShort(mContext, "移动失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    class MoveFolderAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return parentList.size();
        }

        @Override
        public Object getItem(int position) {
            return parentList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            FavoriteFolderBean bean = parentList.get(position);
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.favorite_manager_item, null);
            }
            ImageView ivLeft = (ImageView) convertView.findViewById(R.id.favorite_weblist_pop_item_img);
            TextView tvTitle = (TextView) convertView.findViewById(R.id.favorite_weblist_pop_item_tv);
            ImageView ivRight = (ImageView) convertView.findViewById(R.id.favorite_weblist_pop_item_right);
            ivLeft.setVisibility(View.GONE);
            ivRight.setVisibility(View.INVISIBLE);
            if (bean.isIslastone()) {
                tvTitle.setText(R.string.make_to_top);
            } else {
                tvTitle.setText(bean.getFolderName());
            }
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tvTitle.getLayoutParams();
            layoutParams.leftMargin = ResourceUtils.getDimens(R.dimen.space_20);
            tvTitle.setLayoutParams(layoutParams);
            return convertView;
        }
    }

}
